package com.puzzlebazar.client.squaregrid.view;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.puzzlebazar.client.util.Vec2i;

public class StringDrawable extends Drawable {
	
	private Label label = null;

	/**
	 * Creates an string-based drawable
	 * 
	 * @param name Name of the drawable for future reference (can be null)
	 */
	public StringDrawable(String name) {
		super(name);
		createStringWidget( null );
	}

	/**
	 * Creates an string-based drawable within a single cell
	 * 
	 * @param loc Location of the cell
	 * @param name Name of the drawable for future reference (can be null)
	 */
	public StringDrawable(Vec2i loc, String name) {
		super(loc, name);
		createStringWidget( null );
	}

	/**
	 * Creates an string-based drawable within a single cell
	 * 
	 * @param loc Location of the cell
	 * @param style The style to use for the text (null if none)
	 * @param name Name of the drawable for future reference (can be null)
	 * @param string The string to display
	 */
	public StringDrawable(Vec2i loc, String style, String name, String string) {
		super(loc, name);
		createStringWidget( style );
		setString( string );
	}

	@Override
	public void updateSize( int w, int h ) {
		AbsolutePanel panel = (AbsolutePanel)getWidget();
		if( panel != null ) {
			panel.setPixelSize(w,h);
			panel.getWidget(0).setPixelSize(w,h);
			int textSize = (int)(0.6 * h);
			int stringLength = label.getText().length();
			int widthPad = (int)Math.min(10, 0.25*w);
			if( w < (stringLength * textSize) / 2 + widthPad ) 
				textSize = ((w-widthPad) * 2) / stringLength;
			DOM.setStyleAttribute( label.getElement(), "fontSize", textSize + "px");
		}
	}

	/**
	 * Sets the string to display in this drawable. 
	 * 
	 * @param string The string to display
	 */
	public void setString( String string ) {
		label.setText( string );
	}

	/**
	 * Create the initial system of widget for the string
	 * 
	 * @param style The style to use for the text, null if none
	 */
	private void createStringWidget( String style ) {
		AbsolutePanel topPanel = new AbsolutePanel();
		VerticalPanel panel = new VerticalPanel();
		panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		label  = new Label();
		if( style != null )	label.setStylePrimaryName( style );
		panel.add( label );
		topPanel.add( panel );
		setWidget(topPanel);
	}
	
}
